<template>
  <div>
    <crumbs @goBack="() => {}" :superiorMenu="['库存管理']" currentMenu="库存盘点" style="margin-bottom: 12px" />
    <a-card :bordered="false" style="height: calc(100vh - 175px)">
      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button @click="handleShowFilter" icon="filter" style="margin-right: 10px">
          筛选 <span style="color: #1890ff; margin-left: 5px">{{ searchNum }}</span></a-button
        >
        <a-button @click="showColumn" icon="unordered-list" style="margin-right: 10px"> 设置列 </a-button>
        <div class="right-btn">
          <PubImport
            @updateParentData="updateParentData"
            ref="PubImport"
            formType="7"
            modelName="工序导入模板"
            style="margin-right: 10px"
            v-if="hasButton('process:import')"
          />
          <PubExport
            :exportUrl="exportUrl"
            :columns="columns"
            :propForm="getQueryParams()"
            :selectedRows="chooseArr"
            :fullName="fullName"
            style="margin-right: 10px"
            v-if="hasButton('process:derived')"
          />
          <a-button @click="handleAdd" type="primary" class="btns" v-if="hasButton('process:add')"> +新建 </a-button>
        </div>
      </div>
      <!-- 设置列 -->
      <SetColumn
        columnName="设置列"
        ref="SetColumn"
        v-if="showSetColumn"
        @sureBtn="sureBtn"
        @cancelBtn="showSetColumn = false"
      />
      <!-- table区域-begin -->
      <div>
        <a-table
          v-if="tableShow"
          :key="tableKey"
          ref="table"
          size="middle"
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="false"
          :loading="loading"
          class="j-table-force-nowrap"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            columnTitle: ' ',
            columnWidth: 50,
            onChange: onSelectChange,
          }"
          @change="handleTableChange"
          :scroll="{ x: computedX, y: 'calc(100vh - 300px)' }"
          :components="drag(columns, 'BASE_WORKING_PROCEDURE')"
        >
          <span slot="actions" slot-scope="text, record">
            <a @click="handleEdit(record)" v-if="hasButton('process:edit')">编辑</a>
            <a-divider type="vertical"
                       v-if="hasButton('process:edit') && hasButton('process:delete')" />
            <a-button
              style="color: #f25643; margin-left: 2px; margin-top: 2px; width: 30px"
              type="link"
              @click="handleDelete(record)"
              v-if="hasButton('process:delete')"
            >
              删除</a-button
            >
          </span>
          <!-- title搜索条件开始 -->
          <!-- 输入框搜索 -->
          <div
            v-for="(item, i) in filterDropdownList"
            :key="i"
            style="display: flex; padding: 8px"
            :slot="item.scopedSlots.filterDropdown"
            slot-scope="{ column }"
          >
            <template>
              <a-input
                v-if="item.scopedSlots.filterDropdown === 'searchDropdown'"
                :placeholder="'请输入'[column.title]"
                v-model="queryParam[column.searchIndex]"
                style="width: 188px"
              />
              <j-select-user-by-dep
                v-if="item.scopedSlots.filterDropdown === 'updateBy'"
                v-model="queryParam[`${item.searchIndex}`]"
                :multi="item.multi"
                @changeRow="(a, b, c) => onChangeUser(b || {}, 'updateBy')"
              ></j-select-user-by-dep>
              <j-select-user-by-dep
                v-if="item.scopedSlots.filterDropdown === 'createBy'"
                v-model="queryParam[`${item.searchIndex}`]"
                :multi="item.multi"
                @changeRow="(a, b, c) => onChangeUser(b || {}, 'createBy')"
              ></j-select-user-by-dep>
              <a-select
                :mode="column.multi ? 'multiple' : 'default'"
                v-if="item.scopedSlots.filterDropdown === 'selectDropdown'"
                :placeholder="'请选择'[column.title]"
                allowClear
                style="width: 188px"
                v-model="queryParam[`${column.searchIndex}all`]"
                @change="(a) => changeSelect(a, column.searchIndex)"
                :labelInValue="true"
              >
                <a-select-option v-for="(items, i) in column.options" :key="i" :value="items.key">{{
                  items.label
                }}</a-select-option>
              </a-select>
              <a-button
                v-if="item.scopedSlots.filterDropdown !== 'tooltip'"
                type="primary"
                style="width: 80px; margin-left: 20px"
                @click="searchQuery"
              >
                搜索
              </a-button>
            </template>
          </div>
          <a-icon slot="searchIcon" type="search" />
          <a-icon
            slot="dateIcon"
            slot-scope="filtered"
            type="filter"
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
          <!-- title搜索条件结束 -->
        </a-table>
      </div>
      <!-- table区域-end -->
      <!-- 底部分页 -->
      <div class="tableFooter">
        <div style="display: inline-block; float: right">
          <a-pagination
            :total="ipagination.total"
            v-model="ipagination.current"
            :page-size-options="ipagination.pageSizeOptions"
            :page-size="ipagination.pageSize"
            @change="onChangePage"
            @showSizeChange="onChangePage"
            show-quick-jumper
            show-size-changer
          />
        </div>
      </div>
      <!-- 表格条数 -->
      <div class="tableSelect" :style="{ left: collapsed ? '229px' : '110px' }">
        <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>

        <span
          class="pubColor"
          @click="batchPrintAction"
          style="padding-left: 3px; color: rgb(51, 153, 255); margin-left: 8px; cursor: pointer"
          v-if="hasButton('process:delete')"
          >删除</span
        >
        <span style="margin: 0 20px">{{ `已选 ${selectedRowKeys.length}/${this.dataSource.length} 项` }}</span>
        <span class="pubColor" @click="clearArr" style="color: rgb(51, 153, 255); margin-left: 5px; cursor: pointer"
          >清空</span
        >
      </div>
      <!-- 侧边筛选 -->
      <a-drawer
        width="500"
        height="100vh"
        :bodyStyle="{ background: '#f5f5f5', padding: '0' }"
        :closable="true"
        :visible="showFilter"
        @close="showFilter = false"
      >
        <formSearch ref="dataSearch" @searchDate="searchDate" />
      </a-drawer>
    </a-card>
    <a-modal
      v-if="batchDeletevisible"
      :width="currentEnvironment == 'dingding' ? 1000 : 500"
      :visible="batchDeletevisible"
      :closable="false"
      :confirm-loading="false"
      @cancel="batchDeletevisible = false"
      title="批量删除"
    >
      <batch-ding-print-view v-if="currentEnvironment == 'dingding'" :ids="selectedRowKeys" />
      <div v-if="currentEnvironment != 'dingding'">是否确定批量删除！</div>
      <template slot="footer">
        <a-button key="back" @click="batchDeletevisible = false"> 取消 </a-button>
        <a-button key="submit" type="primary" @click="changeBatchDelete"> 删除 </a-button>
      </template>
    </a-modal>
    <windowForm ref="windowForm" @refresh="searchQuery"></windowForm>
    <windowDetail ref="windowDetail"></windowDetail>
  </div>
</template>

<script>
import moment from 'moment'

import '@/assets/less/TableExpand.less'
import { tableMixinReport } from '@/mixins/tableMixinReport'
import { columns, allColumn } from './column.js'
import tableDragResize from '@/mixins/tableDragResize'
import { API } from '@/api/requestFzs'
import { APILX } from '@/api/requestLx'
import PubImport from '@/components/pubBtn/PubImport.vue'
import PubExport from '@/components/pubBtn/PubExport.vue'

import { getEnableOne } from '@/api/api'
import { downFilePost } from '@/api/manage'
import { mapState } from 'vuex'
import tableDynamicField from '@/mixins/tableDynamicField'
import { hasButton } from '@/utils/hasPermission'
const actionArr = [
  {
    fixed: 'right',
    title: '操作',
    align: 'left',
    dataIndex: 'actions',
    width: 150,
    scopedSlots: { customRender: 'actions' },
  },
]
export default {
  mixins: [tableMixinReport, tableDragResize, tableDynamicField],
  components: {
    windowForm: (resolve) => require(['@/views/baseManagement/workingProcedure/form'], resolve),
    windowDetail: (resolve) => require(['@/views/baseManagement/workingProcedure/detail'], resolve),
    PubImport,
    PubExport,
  },
  data() {
    return {
      formType: 7,
      // 表头
      columns: columns.map((e) => {
        e.align = 'left'
        return e
      }),
      batchDeletevisible: false,
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      selectedRowKeys: [],
      chooseArr: [],
      allRequestList: [],
      currentEnvironment: '',

      actionArr,
      allColumn: allColumn.map((e) => {
        e.align = 'left'
        return e
      }),
      url: {
        list: '/basic/basicProductionProcesses/list',
        methods: 'post',
      },
      tableData: {},
      EntityName: this.BUSI_CONST.Entity.BASE_WORKING_PROCEDURE, //用于表头设计,值保证是唯一的即可
      currentUserId: '',
      tableKey: 1.9,
      exportUrl: '/basic/basicProductionProcesses/exportXls',
      fullName: `工序 ${moment(new Date()).format('YYYY-MM-DD HH:mm')}`,
      sortForm: {
        sortType: '',
        sortColumn: '',
      },
    }
  },
  computed: {
    ...mapState({
      collapsed: (state) => state.user.collapsedAno,
    }),
    computedX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum + 60
    },
  },
  async created() {
    // this.$store.commit('SET_CURRENT_PREFIX', '/jksaas-easyMake/easyMake')

    // getEnableOne({ id: 'WMS_WAREHOUSE_INVENTORY', type: 'add' }).then((res) => {
    //   if (res.result && res.result == 'false') {
    //     this.allColumn = this.allColumn.filter((item) => item.title != '审批状态')
    //     this.columns = this.columns.filter((item) => item.title != '审批状态')
    //   }
    // })
    let currentLogin = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value
    this.currentUserId = currentLogin.id
    // await this.getFields()
  },
  methods: {
    hasButton,
    //导入
    updateParentData() {
      console.log('导入成功了302')
      // let params = this.formatData()
      // this.current = 1
      // let obj = {
      //   pageNo: this.current,
      //   pageSize: this.pageSize,
      //   ...params,
      // }
      this.searchQuery()
    },
    // 筛选传参数据
    formatData() {
      console.log(this.filterForm,'this.filterForm')
      let copyForm = JSON.parse(JSON.stringify(this.queryParam))
      let params = {}
      if (copyForm.statusListStr && copyForm.statusListStr.length > 0) {
        params.statusListStr = copyForm.statusListStr.join(',')
      } else {
        params.statusListStr = ''
      }
      params.orderCode = copyForm.orderCode
      params.goodsName = copyForm.goodsName
      params.goodsSpec = copyForm.goodsSpec
      if (copyForm.planStartTime && copyForm.planStartTime.length > 0) {
        params.planStartTimeBegin = copyForm.planStartTime[0] + ' ' + '00:00:00'
        params.planStartTimeEnd = copyForm.planStartTime[1] + ' ' + '23:59:59'
      } else {
        params.planStartTimeBegin = ''
        params.planStartTimeEnd = ''
      }
      if (copyForm.planEndTime && copyForm.planEndTime.length > 0) {
        params.planEndTimeBegin = copyForm.planEndTime[0] + ' ' + '00:00:00'
        params.planEndTimeEnd = copyForm.planEndTime[1] + ' ' + '23:59:59'
      } else {
        params.planEndTimeBegin = ''
        params.planEndTimeEnd = ''
      }
      params.principalIds = copyForm.principalIds
      params.remark = copyForm.remark
      params.relevanceOrder = copyForm.relevanceOrder
      params.createByIds = copyForm.createByIds
      if (copyForm.createTime && copyForm.createTime.length > 0) {
        params.createTimeBegin = copyForm.createTime[0] + ' ' + '00:00:00'
        params.createTimeEnd = copyForm.createTime[1] + ' ' + '23:59:59'
      } else {
        params.createTimeBegin = ''
        params.createTimeEnd = ''
      }
      return params
    },
    cancel() {},
    onSelectChange(selectedRowKeys, selectedRows) {
      console.log('第一个参数是；', selectedRowKeys)
      console.log('第second个参数是；', selectedRows)
      this.selectedRowKeys = selectedRowKeys
      this.chooseArr = []
      for (let tag of selectedRowKeys) {
        for (let item of this.dataSource) {
          if (tag == item.id) {
            this.chooseArr.push(item)
          }
        }
      }
      this.checkBoxStatus()
    },
    // 全选
    onCheckAllChange(e) {
      console.log('zhehsig', e.target)
      if (e.target.checked) {
        for (let item of this.dataSource) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.chooseArr = this.chooseArr.filter((every) => {
            return every.id != item.id
          })
          this.selectedRowKeys.push(item.id)
          this.chooseArr.push(item)
        }
      } else {
        for (let item of this.dataSource) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.chooseArr = this.chooseArr.filter((every) => {
            return every.id != item.id
          })
        }
      }

      this.checkBoxStatus()
    },
    clearArr() {
      this.selectedRowKeys = []
      this.chooseArr = []
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.dataSource) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        console.log()
        console.log('第一个参数是；', checkValue)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 批量删除
    batchPrintAction() {
      if (this.selectedRowKeys.length > 0) {
        let that = this
        that.$antdConfirm({
          title: '确定要删除工序吗?',
          content: `删除后不可恢复！`,
          onOk() {
            APILX.basicProductionProcessesDeleteBatch({ ids: that.selectedRowKeys.toString() }).then((res) => {
              that.$antdMessage.success(res.message)
              that.batchDeletevisible = false
              that.clearArr()
              that.searchQuery()
            })
          },
          onCancel() {},
        })
      } else {
        this.$antdMessage.warning('请勾选需要批量删除的数据')
      }
      // this.batchDeletevisible = true
    },
    changeBatchDelete() {
      if (this.selectedRowKeys.length <= 0) {
        this.$antdMessage.error('请选择删除数据')
        return
      }
      APILX.basicProductionProcessesDeleteBatch({ ids: this.selectedRowKeys.toString() }).then((res) => {
        this.$antdMessage.success(res.message)
        this.batchDeletevisible = false
        this.clearArr()
        this.searchQuery()
      })
    },
    changeBatchPrint() {
      this.batchDeletevisible = false
    },
    handleAdd() {
      this.$refs.windowForm.initForm()
    },
    handleEdit(v) {
      this.$refs.windowForm.initForm(v)
    },
    /* 删除、批量删除 */
    handleDelete(v) {
      if (v instanceof Array) {
        if (v.length > 0) {
          let that = this
          that.$antdConfirm({
            title: '确定要删除工序吗?',
            content: `删除后不可恢复！`,
            onOk() {
              APILX.basicProductionProcessesDeleteBatch({ ids: v.toString() }).then((res) => {
                if (res.code == 200) {
                  that.$antdMessage.success('删除成功！')
                  that.searchQuery()
                  that.clearArr()
                } else {
                  that.$antdMessage.error('删除失败！')
                }
              })
            },
            onCancel() {},
          })
        } else {
          this.$antdMessage.warning('请勾选需要批量删除的数据')
        }
      } else {
        let that = this
        that.$antdConfirm({
          title: '确定要删除此工序吗?',
          content: `删除后不可恢复！`,
          onOk() {
            APILX.basicProductionProcessesDelete({ id: v.id }).then((res) => {
              if (res.code == 200) {
                that.$antdMessage.success('删除成功！')
                if (that.tableData.length === 1) {
                  that.current = that.current == 1 ? 1 : that.current - 1
                }
                that.searchQuery()

                that.clearArr()
              } else {
                that.$antdMessage.error('删除失败！')
              }
            })
          },
          onCancel() {},
        })
      }
    },
    exportAction(record) {
      let fileName = `库存盘点 ${record.inventoryCode}`
      let postData = {
        id: record.id,
      }
      downFilePost('/wms/wmsWarehouseInventory/exportInventoryDetails', postData).then((data) => {
        if (data.type == 'application/json') {
          const reader = new FileReader() //创建一个FileReader实例
          reader.readAsText(data, 'utf-8') //读取文件,结果用字符串形式表示
          reader.onload = function () {
            //读取完成后,**获取reader.result**
            const msg = JSON.parse(reader.result)
            this.$antdMessage.error(msg.message) //弹出错误提示
          }
          return
        }
        if (!data) {
          this.$antdMessage.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    /* 撤回 */
    handleWithdraw(v) {
      let that = this
      that.$antdConfirm({
        title: '确定撤回吗？',
        content: '撤回后暂不支持再次发起',
        onOk() {
          API.operateRevoke({ flowInstId: v.flowInstId }).then((res) => {
            if (res.code == 200) {
              that.$antdMessage.success(res.message)
              that.loadData(1)
            } else {
              that.$antdMessage.error(res.message)
            }
          })
        },
        onCancel() {},
      })
    },
  },
}
</script>
<style scoped lang="less">
.right-btn {
  float: right;
  display: flex;
  justify-content: flex-end;
  button {
    margin: 0 !important;
  }
}
/deep/.ant-card-body {
  padding: 20px 16px;
}
@import '~@/assets/less/public.less';
@import '~@assets/less/common.less';
</style>
